package com.zone.domain.rebate.service;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.zone.domain.rebate.event.UserRebateEvent;
import com.zone.domain.rebate.model.aggregate.UserRebateCreateOrderAggregate;
import com.zone.domain.rebate.model.entity.DailyBehaviorRebateEntity;
import com.zone.domain.rebate.model.entity.UserBehaviorRebateOrderEntity;
import com.zone.domain.rebate.model.entity.UserRebateCreateOrderEntity;
import com.zone.domain.rebate.model.valobj.BehaviorTypeEnum;
import com.zone.domain.rebate.repository.IBehaviorRebateRepository;
import com.zone.domain.task.model.entity.TaskEntity;
import com.zone.domain.task.model.valobj.TaskState;
import com.zone.types.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/3/3
 */
@Slf4j
@Service
public class BehaviorRebateServiceImpl implements IBehaviorRebateService {
    @Autowired
    private IBehaviorRebateRepository behaviorRebateRepository;
    @Value("${spring.rabbitmq.topic.user_rebate}")
    private String userRebateTopic;

    @Override
    public void createUserBehaviorOrder(UserRebateCreateOrderEntity createOrderEntity) {
        // 参数校验
        if (Strings.isBlank(createOrderEntity.getUserId())) {
            throw new BizException("用户id不能为空");
        }
        if (Objects.isNull(createOrderEntity.getBehaviorTypeEnum())) {
            throw new BizException("用户行为不能为空");
        }
        if (Strings.isBlank(createOrderEntity.getOutBusinessNo())) {
            throw new BizException("业务单号不能为空");
        }
        // 查询行为类型配置信息
        List<DailyBehaviorRebateEntity> rebateConfigList = behaviorRebateRepository.queryDailyBehaviorRebate(createOrderEntity.getBehaviorTypeEnum());
        if (CollectionUtils.isEmpty(rebateConfigList)) {
            log.info("创建用户行为流水单失败，未查询到行为配置信息 behaviorType = {}", createOrderEntity.getBehaviorTypeEnum());
            return;
        }
        // 构造用户返利流水单聚合对象
        List<UserRebateCreateOrderAggregate> createOrderAggregates = Lists.newArrayList();
        for (DailyBehaviorRebateEntity rebateConfig : rebateConfigList) {
            UserRebateCreateOrderAggregate userRebateCreateOrderAggregate = new UserRebateCreateOrderAggregate();
            userRebateCreateOrderAggregate.setUserId(createOrderEntity.getUserId());
            userRebateCreateOrderAggregate.setBehaviorTypeEnum(createOrderEntity.getBehaviorTypeEnum());

            // 用户返利流水单
            UserBehaviorRebateOrderEntity userBehaviorRebateOrderEntity = new UserBehaviorRebateOrderEntity();
            userBehaviorRebateOrderEntity.setUserId(createOrderEntity.getUserId());
            userBehaviorRebateOrderEntity.setOrderId(RandomStringUtils.randomNumeric(12));
            userBehaviorRebateOrderEntity.setBehaviorType(createOrderEntity.getBehaviorTypeEnum());
            userBehaviorRebateOrderEntity.setRebateDesc(rebateConfig.getRebateDesc());
            userBehaviorRebateOrderEntity.setRebateType(rebateConfig.getRebateType());
            userBehaviorRebateOrderEntity.setRebateConfig(rebateConfig.getRebateConfig());
            String bizId = String.format("%s_%s_%s_%s", createOrderEntity.getUserId(),
                    createOrderEntity.getBehaviorTypeEnum().getCode(),
                    rebateConfig.getRebateType(),
                    createOrderEntity.getOutBusinessNo());
            userBehaviorRebateOrderEntity.setBizId(bizId);
            userBehaviorRebateOrderEntity.setOutBusinessNo(createOrderEntity.getOutBusinessNo());
            userBehaviorRebateOrderEntity.setOrderDate(LocalDate.now());
            userRebateCreateOrderAggregate.setUserBehaviorRebateOrderEntity(userBehaviorRebateOrderEntity);

            // 消息发送任务
            UserRebateEvent userRebateEvent = new UserRebateEvent();
            userRebateEvent.setUserId(createOrderEntity.getUserId());
            userRebateEvent.setBehaviorType(rebateConfig.getBehaviorType().getCode());
            userRebateEvent.setRebateType(rebateConfig.getRebateType().getCode());
            userRebateEvent.setRebateConfig(rebateConfig.getRebateConfig());

            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(createOrderEntity.getUserId());
            taskEntity.setTopic(userRebateTopic);
            taskEntity.setMessageId(RandomStringUtils.randomNumeric(11));
            taskEntity.setMessage(JSON.toJSONString(userRebateEvent));
            taskEntity.setState(TaskState.CREATE);
            userRebateCreateOrderAggregate.setTaskEntity(taskEntity);
            createOrderAggregates.add(userRebateCreateOrderAggregate);
        }
        // 创建返利流水单
        behaviorRebateRepository.createRebateOrder(createOrderAggregates);
    }

    @Override
    public List<UserBehaviorRebateOrderEntity> queryUserBehaviorRebateOrderList(String userId, BehaviorTypeEnum behaviorType, LocalDate orderDate) {
        return behaviorRebateRepository.queryUserBehaviorRebateOrderList(userId, behaviorType, orderDate);
    }
}
